﻿using Facebook;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace FriendAnalyzer.Infrastructure.Facebook.DataAccess
{
    internal class FacebookConnection
    {
        private FacebookClient _api;

        public FacebookConnection(FacebookClient api)
        {
            _api = api;
        }

        public async Task<IEnumerable<TDeserialized>> ConvertItemsFromJson<TDeserialized>(string json)
        {
            var deserialized = await JsonConvert.DeserializeObjectAsync<BaseResult<TDeserialized>>(json.ToString());

            return deserialized.Data;
        }
        public async Task<TDeserialized> ConvertItemFromJson<TDeserialized>(string json)
        {
            var deserialized = await JsonConvert.DeserializeObjectAsync<TDeserialized>(json.ToString());

            return deserialized;
        }

        public async Task<IEnumerable<TFacebookItem>> ExecuteQueryAsync<TFacebookItem>(string query)
        {
            var json = await _api.GetTaskAsync("/fql", new
            {
                q = query,
            });

            var result = await ConvertItemsFromJson<TFacebookItem>(json.ToString());

            return result;
        }
        public async Task<TFacebookItem> ExecuteGraphApiCall<TFacebookItem>(string url)
        {
            var json = await _api.GetTaskAsync(url);

            var result = await ConvertItemFromJson<TFacebookItem>(json.ToString());

            return result;
        }
    }
}
